package cn.adelyn.blog.blogmanager.dao;

import cn.adelyn.blog.blogmanager.dao.mapper.BlogTagMapper;
import cn.adelyn.blog.blogmanager.pojo.bo.InsertBlogDecryptBO;
import cn.adelyn.blog.blogmanager.pojo.model.BlogTagModel;
import cn.adelyn.blog.blogmanager.pojo.model.TagModel;
import cn.adelyn.blog.blogmanager.pojo.vo.TagVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class BlogTagDAOService {

    @Autowired
    BlogTagMapper blogTagMapper;

    public void insertBlogTag(InsertBlogDecryptBO insertBlogDecryptBO) {
        List<BlogTagModel> blogTagModelList = genBlogTagList(insertBlogDecryptBO);
        blogTagMapper.insertBatch(blogTagModelList);
    }

    public void insertBlogTag(long blogId, long tagId) {
        BlogTagModel blogTagModel = new BlogTagModel();
        blogTagModel.setBlogId(blogId);
        blogTagModel.setTagId(tagId);
        blogTagMapper.insert(blogTagModel);
    }

    public List<TagVO> selectBlogTags(long blogId) {
        MPJLambdaWrapper<BlogTagModel> mpjLambdaWrapper = new MPJLambdaWrapper<>(BlogTagModel.class)
                .select(TagModel::getTagId, TagModel::getTagName)
                .eq(BlogTagModel::getBlogId, blogId)
                .leftJoin(TagModel.class, TagModel::getTagId, BlogTagModel::getTagId);

        return blogTagMapper.selectJoinList(TagVO.class, mpjLambdaWrapper);
    }

    public long selectTagBlogsCount(long tagId) {
        QueryWrapper<BlogTagModel> queryWrapper = new QueryWrapper();
        queryWrapper.lambda()
                .eq(BlogTagModel::getTagId, tagId);
        return blogTagMapper.selectCount(queryWrapper);
    }

    public void deleteBlogTag(long blogId, long tagId) {
        QueryWrapper<BlogTagModel> queryWrapper = new QueryWrapper();
        queryWrapper.lambda()
                .eq(BlogTagModel::getBlogId, blogId)
                .eq(BlogTagModel::getTagId, tagId);
        blogTagMapper.delete(queryWrapper);
    }

    public void deleteBlogTag(long blogId) {
        blogTagMapper.deleteById(blogId);
    }

    private List<BlogTagModel> genBlogTagList(InsertBlogDecryptBO insertBlogDecryptBO) {
        List<BlogTagModel> blogTagModelList = new ArrayList<>();
        insertBlogDecryptBO.getTagIdList().forEach(tagId ->{
            BlogTagModel blogTagModel = new BlogTagModel();
            blogTagModel.setTagId(tagId);
            blogTagModel.setBlogId(insertBlogDecryptBO.getBlogId());
            blogTagModelList.add(blogTagModel);
        });
        return blogTagModelList;
    }
}
